package com.zhou.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.zhou.common.constant.ProductConstant;
import com.zhou.common.to.SkuReductionTo;
import com.zhou.common.to.SpuBoundTo;
import com.zhou.common.to.es.SkuEsModel;
import com.zhou.common.utils.R;
import com.zhou.gulimall.product.dao.SpuInfoDescDao;
import com.zhou.gulimall.product.entity.*;
import com.zhou.gulimall.product.fegin.CouponFeignService;
import com.zhou.gulimall.product.fegin.SearchFeignService;
import com.zhou.gulimall.product.fegin.WareFeignService;
import com.zhou.gulimall.product.service.*;
import com.zhou.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhou.common.utils.PageUtils;
import com.zhou.common.utils.Query;

import com.zhou.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    SpuInfoDescDao descDao;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;
    @Override
    /**
     * 分页展示列表
     */
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 大保存
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        
        this.saveBaseSpuInfo(spuInfoEntity);
        Long kkid = spuInfoEntity.getId();
        log.info("+++++++++++++++++++++++++++",kkid);
        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> descript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();


        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",descript));
        this.saveSpuInfoDesc(spuInfoDescEntity);
        //3.保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(baseAttrs1 -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(baseAttrs1.getAttrId());
            AttrEntity byId = attrService.getById(baseAttrs1.getAttrId());
            attrValueEntity.setAttrName(byId.getAttrName());
            attrValueEntity.setAttrValue(baseAttrs1.getAttrValues());
            attrValueEntity.setQuickShow(baseAttrs1.getShowDesc());
            attrValueEntity.setSpuId(spuInfoEntity.getId());
            return attrValueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveBatch(collect);
        //5.保存spu的积分信息 跨数据库 gulimall_sms => sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r2 = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r2.getCode() != 0){
            log.error("远程保存spu信息失败");
        }
        //6.保存当前spu对应的sku信息
        //6.1 sku的基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (skus != null || skus.size()>0){
            for (Skus item : skus) {//提前找到默认图片
                String defaultImg = "";
                for (Images img : item.getImages()) {
                    if (img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0l);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);

                //6.2 sku的图片信息 pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> collect1 = item.getImages().stream().map(imafe -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(imafe.getImgUrl());
                    skuImagesEntity.setDefaultImg(imafe.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //true 需要 false过滤
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //TODO 没有图片路径的无需保存
                skuImagesService.saveBatch(collect1);


                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect2 = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect2);

                //6.3 sku的销售属性 pms_sku_sale_attr_value
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0){
                        log.error("远程保存sku满减信息失败");
                    }
                    //6.4 sku的优惠，满减等信息：跨数据库
                }


            }
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        descDao.insert(spuInfoDescEntity);
    }

    @Override
    public PageUtils queryPageCondtion(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(params.get("brandId")) && !brandId.equals("0")){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
               wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 商品上架
     */
    @Override
    public void up(Long spuId) {
        //1.1 查询出当前spuId对应的所有spu信息。品牌的名字。
        QueryWrapper<SkuInfoEntity> skuInfoEntityQueryWrapper = new QueryWrapper<>();
        skuInfoEntityQueryWrapper.eq("spu_id",spuId);
        List<SkuInfoEntity> list = skuInfoService.list(skuInfoEntityQueryWrapper);
        System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
        System.out.println(list);

        List<Long> skuIdList = list.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 5查询当前sku的所有需要用来检索的规格属性
        List<ProductAttrValueEntity> attrValueEntities = attrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = attrValueEntities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //过滤掉不可检索的属性规格
        List<Long> searchAttrId = attrService.selectSearchAttrs(attrIds);
        //TODO idSet.contains(item.getAttrId);
        Set<Long> idSet = new HashSet<>(searchAttrId);

        List<SkuEsModel.Attrs> collect = attrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(itm -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(itm, attrs1);
            return attrs1;
        }).collect(Collectors.toList());


        //TODO 1发送远程调用，查询库存系统=》查看是否库存：true？false
        Map<Long, Boolean> map = null;
        //调用远程服务可能会发生网络异常，trycatch处理
        try {
            R r = wareFeignService.getHasStock(skuIdList);
            //将查询后的结果封装成一个map集合
            System.out.println("===============");
            System.out.println(r.get("data"));
            //Object data = hasStock.get("data");
            //data = "[{skuId=37, hasStock=true}, {skuId=38, hasStock=true}]"
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
          map = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,item -> item.getHasStock()));
//            for (SkuHasStockVo vo : r.getData(typeReference)) {
//                map.put(vo.getSkuId(),vo.getHasStock());
//            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("库存服务查询异常：原因{}",e.getMessage());
            log.error(e.toString());
        }
        //封装每个sku的信息
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> upProducts = list.stream().map(sku -> {
            //.组装需要的数据类型
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);
            /**
             * 需要额外处理的属性
             *      1.skuimage,skuprice,hasStock,hotScore,
             *      2.brandName;brandImg;catalogName;
             *      3.public static class Attrs{
             *         private Long attrId;
             *         private String attrName;
             *         private String attrValue;
             *     }
             */
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            //TODO 1发送远程调用，查询库存系统=》查看是否库存：true？false
            //设置库存信息
            if (finalMap == null){
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalMap.get(sku.getSkuId()));
            }
            //TODO 2热度评分。默认0
            esModel.setHotScore(0L);
            //TODO 3查询品牌和分类名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());

            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            //TODO 4根据catalogId查询分类名字  catalogName;
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(category.getName());

            //TODO 5查询当前sku的所有需要用来检索的规格属性==》一个sku对应的规格属性都一样，放到外面
            esModel.setAttrs(collect);
            return esModel;
        }).collect(Collectors.toList());

        //TODO 6将封装好的数据发送给es进行保存 调用gulimall-search服务
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0){
            //远程调用成功
            //TODO 7 改变上架商品spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //todo 重复调用？接口幂等性。重试机制
        }

    }

}